import { ConfigureService } from '@app/configure';
import { Injectable } from '@nestjs/common';

//const container = require('rhea');
//const crypto = require('crypto');
import * as container from 'rhea'
import { randomUUID, createHmac } from 'crypto'

@Injectable()
export class AliIotSubscribeClientService {

  connect(config:{uid:string; regionId:string; accessKey:string; accessSecret:string; consumerGroupId:string; instanceId?:string}, callback:(topic:string, content:string, messageId:any) => void) {
    const timestamp = Math.floor(Date.now() / 1000)
    let username = `${randomUUID()}|authMode=aksign,signMethod=hmacsha1,timestamp=${timestamp},authId=${config.accessKey}`
    if(config.instanceId) {
      username += (`,iotInstanceId=${config.instanceId}`)
    }

    username += (`,consumerGroupId=${config.consumerGroupId}|`)

    const password = Buffer.from(createHmac('sha1', config.accessSecret).update('authId='+ config.accessKey +'&timestamp=' + timestamp).digest()).toString('base64')

    var connection = container.connect({
        //接入域名，请参见AMQP客户端接入说明文档。
        'host': `${config.uid}.iot-amqp.${config.regionId}.aliyuncs.com`,
        'port': 5671,
        'transport':'tls',
        'reconnect':true,
        'idle_time_out':60000,
        //userName组装方法，请参见AMQP客户端接入说明文档。
        'username': username, 
        //计算签名，password组装方法，请参见AMQP客户端接入说明文档。
        'password': password,
    })


    connection.open_receiver();

    connection.on('message', function (context) {
        var msg = context.message;
        callback(msg.application_properties.topic, Buffer.from(msg.body.content).toString(), msg.message_id)
        //发送ACK，注意不要在回调函数有耗时逻辑。
        context.delivery.accept();
    });


  }
}
